package net.melon.sysres;

import java.io.File;

import net.esj.basic.core.engine.config.MelonConfig;
import net.esj.basic.utils.Validators;
import net.esj.basic.core.utils.PropertiesInfo;

public abstract class Configer {

	public static final String UPLOADER_DEFAULT_DIR = "sysres_uploads";
	
	public static File getSysUploadRoot(){
		 String d = MelonConfig.getProperty(PropertiesInfo.MELON_PROP_SYS_UPLOAD_ROOT);
		 if(Validators.isEmpty(d)){
			 d = System.getProperties().getProperty("user.dir");
		 }
		 if(!d.endsWith(File.separator)){
			 d+=File.separator;
		 }
		 d+=UPLOADER_DEFAULT_DIR;
		 File f = new File(d);
		 if(!f.exists()){
			 f.mkdirs();
		 }
		return f;
	}
	
	public static String getSysUploadRootPath(){
		 String d = MelonConfig.getProperty(PropertiesInfo.MELON_PROP_SYS_UPLOAD_ROOT);
		 if(Validators.isEmpty(d)){
			 d = System.getProperties().getProperty("user.dir");
		 }
		 if(!d.endsWith(File.separator)){
			 d+=File.separator;
		 }
		 d+=UPLOADER_DEFAULT_DIR;
		return d;
	}

	public static File[] getChildFiles(String absPath){
		if(Validators.isEmpty(absPath)){
			return getSysUploadRoot().listFiles();
		}
		absPath = getSysUploadRootPath()+absPath;
		File f = new File(absPath);
		return f.listFiles();
	}
	
	public static void mkDir(String parentPath,String name){
		File parent = null;
		if(Validators.isEmpty(parentPath)){
			parent = getSysUploadRoot();
		}else{
			parent  = new File(getSysUploadRootPath()+parentPath);
		}
		File f = new File(parent, name);
		f.mkdirs();
	}
	
	public static void rename(File f,String name){
		String fname = f.getAbsolutePath();
		fname = fname.substring(0, fname.lastIndexOf(File.separator));
		fname = fname+File.separator+name;
		File newFile = new File(fname);
		f.renameTo(newFile);
	}
	
	public static String getOppositePath(File file){
		String path = file.getAbsolutePath();
		String root = getSysUploadRootPath();
		return path.substring(root.length()); 
	}

}
